<template>
  <div
    :class="['element-block-wrapper', active ? 'active' : '']"
    @dblclick="dbHandleClick"
    @click="handleClick"
    :style="style"
  >
    <img draggable="false" :src="TilesImage[element.id]" class="icon" />
  </div>
</template>

<script setup lang="ts">
import { TilesImage } from "@/constants";
import type { CommonProperty } from "@/element/common/CommonProperty";
import { useElementStyle } from "@/hooks/useStyle";
import { useElementRenderStore } from "@/stores/common/elementRender";
import { useSelectStore } from "@/stores/editMap/elementSelect";
import { useShortcutStore } from "@/stores/editMap/shortcut";
import { computed } from "vue";

const { element } = defineProps<{
  element: CommonProperty;
}>();
const { useClickDelete, selectMapElement, beginExchange } = $(
  useShortcutStore()
);
const { removeItem } = useElementRenderStore();
const {
  setCurrentSelectedElement,
  getCurrentSelectedElement,
  mapActiveElement,
  isMapElement,
} = $(useSelectStore());

const active = computed(() => {
  return (
    mapActiveElement === element.getRenderKey() &&
    (selectMapElement || beginExchange)
  );
});

const dbHandleClick = () => {
  removeItem(element);
};

function dealwithDelete() {
  if (useClickDelete) {
    dbHandleClick();
  }
}

function dealwithMapElement() {
  if (selectMapElement) {
    setCurrentSelectedElement(element, true);
  }
}

function dealwithExchange() {
  // 地图活动的元素与当前元素一致，取消选中,放后面会直接清空元素
  if (mapActiveElement === element.getRenderKey()) {
    return setCurrentSelectedElement(null, false);
  }

  // 选中的元素非地图元素
  if (!isMapElement || !mapActiveElement) {
    return setCurrentSelectedElement(element, true);
  }

  // 元素互换
  const ele = getCurrentSelectedElement();
  if (ele) {
    const beforeEle = { x: ele?.x, y: ele?.y };
    ele?.movePosition(element);
    element.movePosition(beforeEle);
    setCurrentSelectedElement(null, false);
  }
}

const handleClick = () => {
  dealwithDelete();
  dealwithMapElement();
  if (beginExchange) dealwithExchange();
};

const { style } = $(useElementStyle(element));
</script>

<style scoped lang="scss">
.element-block-wrapper {
  position: absolute;

  &.active {
    box-shadow: 0px 0px 0px 2px rgb(186 136 7);
    z-index: 1;
  }

  .icon {
    width: 100%;
  }
}
</style>
